<?php
	
	//ref 1
	$weightDefault = 1;
	//ref 1
	$weightParam = 1;
	//ref 0.8     /// 0.95
	$weightSynonyme = 0.75;
	//ref 1    ///0.6
	$weightSons = 0.6;
	//0.95 ref    ///0.5
	$weightDataProp = 0.5;
	//peut d'influence 0.5    ///0.5
	$weightObjProp = 0.5;
	
	$weightClasses = 0.9;
	$weightIndividuals = 0.9;
	
	function searchSimple($queryTyped) {
	
		$splitParamsSearch = preg_split("/[\s,;.'-:!?&~]+/",$queryTyped);
		
		
		//récupération des mots vides
		$listeEmptyWordsTmp = array();
		$fp = fopen("./src/MotsBruit.txt","r"); //lecture du fichier
		while (!feof($fp)) { //on parcourt toutes les lignes
			$line=strtolower(trim(fgets($fp, 4096)));
			array_push($listeEmptyWordsTmp,$line ); // lecture du contenu de la ligne
		}		
		
		//print_r($listeEmptyWordsTmp);
		//var_dump($$listeEmptyWordsTmp);
		
		$listeLematisedParamSearch = array();
		//keep only search param whose word is not an empty word
		foreach($splitParamsSearch as $param){
			if(!in_array($param, $listeEmptyWordsTmp)){
				//On lématise le mot si le mot fait plus de 6 caractère
				if(strlen($param) > 6){
					array_push($listeLematisedParamSearch,substr($param,0,6));
				}else{						
					array_push($listeLematisedParamSearch,$param);
				}
			}
		}
		
		$numerateurCosinusPertinence = array();
		$sommeYDenominateur = array();
		$sommeXDenominateur = array();
		foreach($listeLematisedParamSearch as $param){
			//echo "param : ".$param.'<br/>';
			//On récupère les termNodes stockés en base correspondant à ceux 
			$query=$GLOBALS['bdd']->prepare('	SELECT term.value as termValue, termNode.frequency as termNodeFrequency,  node.path as nodePath, node.idNode as idNode, termnode.position as termnodePosition, termnode.weight as termnodeWeight, document.name as documentName, document.path as documentPath
									FROM term, node, termNode, document
									WHERE term.value = :search
									and termNode.idTerm = term.idTerm
									and node.idNode = termNode.idNode 
									and node.idDocument = document.idDocument
								');
			$query->bindValue(':search',$param, PDO::PARAM_STR);
			$query->execute();
			$results =  $query->fetchAll();
			$query->closeCursor();
			//echo '<p> Il y a '.count($results).' r&eacute;sultats à '.$param.'</p><br/>';
			
				foreach($results as $result)
				{
					
					//Tableau contenant en KEY : l'idNode et en valeur le poid du term
					//On additionne le poids des termes contenu dans les paramètres de recherche si ils sont dans le même noeud 
					//Sinon on crée à chaque fois une nouvelle clé-valeur dans le tableau
					
					//Calcul du numerateur de la mesure du cosinus
					if(array_key_exists($result->idNode, $numerateurCosinusPertinence)){
						//Poids du parametre * poids du termNode en base
						//Pois en du parametre supposé à 1
						$x = 1;
						$numerateurCosinusPertinence[$result->idNode] += $x *$result->termnodeWeight;
					}else{
						//Poids du parametre * poids du termNode en base
						//Pois en du parametre supposé à 1
						$x=1;
						$numerateurCosinusPertinence[$result->idNode] = $x *$result->termnodeWeight;
					}
						
					//Traitement des terms nodes	
					if(array_key_exists($result->idNode, $sommeYDenominateur)){
						$carreY = $result->termnodeWeight * $result->termnodeWeight;
						$sommeYDenominateur[$result->idNode] += $carreY;
						
					}else{
						$carreY = $result->termnodeWeight * $result->termnodeWeight;
						$sommeYDenominateur[$result->idNode] = $carreY;	
					}
					
					//Traitement des parametres de la requete
					if(array_key_exists($result->idNode, $sommeXDenominateur)){
						$carreX = 1*1;
						$sommeXDenominateur[$result->idNode] += $carreX;
						
					}else{
						$carreX= 1*1;
						$sommeXDenominateur[$result->idNode] = $carreX;	
					}	
				}
				
				
		}
		
		$keys = array_keys($numerateurCosinusPertinence);
		$valueNumerateur = array_values($numerateurCosinusPertinence);
		$valueXDenominateur = array_values($sommeXDenominateur);
		$valueYDenominateur = array_values($sommeYDenominateur);
		
		$nodesPertinence = array();
		for($i = 0; $i < count($numerateurCosinusPertinence); $i++){
			$valueDenominateur = sqrt($valueXDenominateur[$i] * $valueYDenominateur[$i]);
			$valuePertinence = $valueNumerateur[$i] / $valueDenominateur;
			
			//echo "<br/>valeur numerateur : ".$valueNumerateur[$i]." / valeur denominateur : ".$valueDenominateur." valeur pertinence ".$valuePertinence;
			$nodesPertinence[$keys[$i]] = $valueNumerateur[$i] / $valueDenominateur;
		}
		
		//On trie le tableau contenant le poids des nodes par ordre décroissant (du plus gros poids (+ pertinent)
		// au plus petit (- pertinent)
		asort($nodesPertinence);
		
		$results = array();
		$i = 0;
		foreach($nodesPertinence as $key => $value){
			//ON recuperee le noeud et le document de l'idNode pertinent et on l'affiche dans un bloc
			$query=$GLOBALS['bdd']->prepare('	SELECT node.path as nodePath, document.name as documentName
									FROM node, document
									WHERE node.idNode = :nodeId
									and document.idDocument = node.idDocument
								');
			$query->bindValue(':nodeId',$key, PDO::PARAM_INT);
			$query->execute();
			$resultsQueries =  $query->fetchAll();
			$query->closeCursor();
			
			foreach($resultsQueries as $resultsQuery){
				$results[$i] = $resultsQuery;
			}
			$i++;
		}
		
		return $results;
	}
	
	function search($queryTyped) {
	
		$splitParamsSearch = preg_split("/[\s,;.'-:!?&~]+/",$queryTyped);
		
		
		//récupération des mots vides
		$listeEmptyWordsTmp = array();
		$fp = fopen("./src/MotsBruit.txt","r"); //lecture du fichier
		while (!feof($fp)) { //on parcourt toutes les lignes
			$line=strtolower(trim(fgets($fp, 4096)));
			array_push($listeEmptyWordsTmp,$line ); // lecture du contenu de la ligne
		}		
		
		
		//Key => Term value AND Value => String Array
		$synonymesParams = array();
		$sonsParams = array();
		$dataPropParams = array();
		$objPropParams = array();
		$requestParams = array();
		$classesParams = array();
		$individualsParams = array();
		
		$listeLematisedParamSearch = array();
		//keep only search param whose word is not an empty word
		foreach($splitParamsSearch as $param){
			//Si ce n'est pas un mot vide
			if(!in_array($param, $listeEmptyWordsTmp) && $param != ""){
				 if(strlen($param)>6){
					$paramLematise = strtolower(mb_substr($param,0,6,'UTF-8'));
				}else{
					$paramLematise = strtolower($param);
				} 

				//For each param get synonyme, sons label, object properties, data properties

				$result = getSynonyme($paramLematise);
				$strResults = getContentResults($result);

				//echo "<br/>Param pour getSynonyme :".$param. " / nb : ".count($strResults);
				foreach($strResults as $synonyme){
					//echo "<br/>Param : ".$param." / syno : ".$synonyme;
					if(strlen($synonyme) > 6){
						
						$synonymesParams[strtolower(mb_substr($synonyme,0,6,'UTF-8'))] =  $param;
						if(!in_array(strtolower(mb_substr($synonyme,0,6,'UTF-8')),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower(mb_substr($synonyme,0,6,'UTF-8')));
						}
						
					}else{
						$synonymesParams[strtolower($synonyme)] =  $param;
						if(!in_array(strtolower($synonyme),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower($synonyme));
						}
						
					}
					
				}
				
			
				$result = getSonsLabel($paramLematise);
				$strResults = getContentResults($result);
				foreach($strResults as $son){
					if(strlen($son) > 6){
						$sonsParams[strtolower(mb_substr($son,0,6,'UTF-8'))] = $param;
						if(!in_array(strtolower(mb_substr($son,0,6,'UTF-8')),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower(mb_substr($son,0,6,'UTF-8')));
						}
						
					}else{
						$sonsParams[strtolower($son)] =  $param;
						if(!in_array(strtolower($son),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower($son));
						}
						
					}
					
				}
				
				$result = getDataProperties($paramLematise);
				$strResults = getContentResults($result);
				foreach($strResults as $dataProp){
					if(strlen($dataProp) > 6){
						$dataPropParams[strtolower(mb_substr($dataProp,0,6,'UTF-8'))] =  $param;
						if(!in_array(strtolower(mb_substr($dataProp,0,6,'UTF-8')),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower(mb_substr($dataProp,0,6,'UTF-8')));
						}
						
					}else{
						$dataPropParams[strtolower($dataProp)] =  $param;
						if(!in_array(strtolower($dataProp),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower($dataProp));
						}
						
					}
					
				}
				
				$result = getClasses($paramLematise);
				$strResults = getContentResults($result);
				//echo "<br/>Param pour getClasses :".$param. " / nb : ".count($strResults);
				foreach($strResults as $class){
					if(strlen($class) > 6){
						$classesParams[strtolower(mb_substr($class,0,6,'UTF-8'))] =  $param;
						if(!in_array(strtolower(mb_substr($class,0,6,'UTF-8')),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower(mb_substr($class,0,6,'UTF-8')));
						}
					}else{
						$classesParams[strtolower($class)] =  $param;
						if(!in_array(strtolower($class),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower($class));
						}
						
					}
				}
				
				$result = getIndividuals($paramLematise);
				$strResults = getContentResults($result);
				//echo "<br/>Param pour getIndividuals :".$param. " / nb : ".count($strResults);
				foreach($strResults as $individual){
					if(strlen($individual) > 6){
						$individualsParams[strtolower(mb_substr($individual,0,6,'UTF-8'))] =  $param;
						if(!in_array(strtolower(mb_substr($individual,0,6,'UTF-8')),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower(mb_substr($individual,0,6,'UTF-8')));
						}
					}else{
						$individualsParams[strtolower($individual)] =  $param;
						if(!in_array(strtolower($individual),$listeLematisedParamSearch)){
							array_push($listeLematisedParamSearch,strtolower($individual));
						}
						
					}
				}
				
			
				//on stocke les synonymes , sons etc dans PARAMS
				
				//On lématise le mot si le mot fait plus de 6 caractère
				if(strlen($param) > 6){
					array_push($listeLematisedParamSearch,strtolower(mb_substr($param,0,6,'UTF-8')));
					$requestParams[strtolower(mb_substr($param,0,6,'UTF-8'))] =  $param;
					
				}else{						
					array_push($listeLematisedParamSearch, $param);
					$requestParams[strtolower($param)] =  $param;
				}
			}
		}
		echo "<br/>Synonymes :";
		var_dump($synonymesParams);
		echo "<br/>Sons :";
		var_dump($sonsParams);
		echo "<br/>Data properties :";
		var_dump($dataPropParams);
		echo "<br/>Object properties :";
		var_dump($objPropParams);
		echo "<br/>Classes for instances :";
		var_dump($classesParams);
		echo "<br/>Instances of classes :";
		var_dump($individualsParams);
		
		$numerateurCosinusPertinence = array();
		$sommeYDenominateur = array();
		$sommeXDenominateur = array();
		
		//On récupère les termNodes stockés en base correspondant à ceux 
		$request = buildTermRequest($listeLematisedParamSearch);
		//echo "La requete est ".$request;
		$query=$GLOBALS['bdd']->query($request);
		//$query->execute($request);
		$results =  $query->fetchAll();
		$query->closeCursor();
	
		//Key : idNode and values : array containing parent request param for a Node
		$parentTermsForNode = Array();
		foreach($results as $result)
		{
			$newParentTermForNode = 0;
			$parentTerm = getParentTerm($result->termValue, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $classesParams, $individualsParams);
			
			if(array_key_exists($result->idNode, $parentTermsForNode)){
				$tabParentTerms = Array();
				$tabParentTerms = $parentTermsForNode[$result->idNode];
				//Si le paramètre parent de la requete est deja stocké pour le node on ne le stocke pas à nouveau
				if(!in_array($parentTerm, $tabParentTerms)){
					array_push($tabParentTerms,$parentTerm);
					$parentTermsForNode[$result->idNode] = $tabParentTerms;
					$newParentTermForNode = 1;
				}
			}else{
				$tabParentTerms = Array();
				array_push($tabParentTerms,$parentTerm);
				$parentTermsForNode[$result->idNode] = $tabParentTerms;
				
			}
			
			//Tableau contenant en KEY : l'idNode et en valeur le poid du term
			//On additionne le poids des termes contenu dans les paramètres de recherche si ils sont dans le même noeud 
			//Sinon on crée à chaque fois une nouvelle clé-valeur dans le tableau
			
			//Calcul du numerateur de la mesure du cosinus
			if(array_key_exists($result->idNode, $numerateurCosinusPertinence)){
				//Poids du parametre * poids du termNode en base
				//Pois en du parametre supposé à 1
				
				$x = getWeight($result->termValue, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $newParentTermForNode, $classesParams, $individualsParams );
				
				$numerateurCosinusPertinence[$result->idNode] += $x *$result->termnodeWeight;
			}else{
				//Poids du parametre * poids du termNode en base
				//Pois en du parametre supposé à 1
				$x = getWeight($result->termValue, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $newParentTermForNode, $classesParams, $individualsParams);
				
				$numerateurCosinusPertinence[$result->idNode] = $x *$result->termnodeWeight;
			}
				
			//Traitement des terms nodes	
			if(array_key_exists($result->idNode, $sommeYDenominateur)){
				$carreY = $result->termnodeWeight * $result->termnodeWeight;
				$sommeYDenominateur[$result->idNode] += $carreY;
				
			}else{
				$carreY = $result->termnodeWeight * $result->termnodeWeight;
				$sommeYDenominateur[$result->idNode] = $carreY;	
			}
			
			//Traitement des parametres de la requete
			if(array_key_exists($result->idNode, $sommeXDenominateur)){
				$x = getWeight($result->termValue, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $newParentTermForNode, $classesParams, $individualsParams);
				$carreX = $x*$x;

				$sommeXDenominateur[$result->idNode] += $carreX;
				
			}else{
				$x = getWeight($result->termValue, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $newParentTermForNode, $classesParams, $individualsParams);
				$carreX= $x*$x;
				
				$sommeXDenominateur[$result->idNode] = $carreX;	
			}	
		}

		
		$keys = array_keys($numerateurCosinusPertinence);
		$valueNumerateur = array_values($numerateurCosinusPertinence);
		$valueXDenominateur = array_values($sommeXDenominateur);
		$valueYDenominateur = array_values($sommeYDenominateur);
		
		$nodesPertinence = array();
		for($i = 0; $i < count($numerateurCosinusPertinence); $i++){
			$valueDenominateur = sqrt($valueXDenominateur[$i] * $valueYDenominateur[$i]);
			$valuePertinence = $valueNumerateur[$i] / $valueDenominateur;
			
			//echo "<br/>valeur numerateur : ".$valueNumerateur[$i]." / valeur denominateur : ".$valueDenominateur." valeur pertinence ".$valuePertinence;
			$nodesPertinence[$keys[$i]] = $valueNumerateur[$i] / $valueDenominateur;
		}
		
		//On trie le tableau contenant le poids des nodes par ordre décroissant (du plus gros poids (+ pertinent)
		// au plus petit (- pertinent)
		asort($nodesPertinence);
		
		
		$results = array();
		$i = 0;
		foreach($nodesPertinence as $key => $value){
			//ON recuperee le noeud et le document de l'idNode pertinent et on l'affiche dans un bloc
			$query=$GLOBALS['bdd']->prepare('	SELECT node.path as nodePath, document.name as documentName
									FROM node, document
									WHERE node.idNode = :nodeId
									and document.idDocument = node.idDocument
								');
			$query->bindValue(':nodeId',$key, PDO::PARAM_INT);
			$query->execute();
			$resultsQueries =  $query->fetchAll();
			$query->closeCursor();
			
			foreach($resultsQueries as $resultsQuery){
				$results[$i] = $resultsQuery;
			}
			$i++;
		}
		
		return $results;
	}
	
	function display_results($results, $nbResults) {
		$resultDisplayed="";
		if ($nbResults > count($results)) {
			$nbResults = count($results);
		}
		for($i=0; $i < $nbResults; $i++){
			$resultDisplayed .= "<br/>Collection/".$results[$i]->documentName." ".$results[$i]->nodePath." 1";
		}
		return $resultDisplayed;
	}
	
	function stock_node_path_results($results, $nbResults) {
		$tab;
		if ($nbResults > count($results)) {
			$nbResults = count($results);
		}
		for($i=0; $i < $nbResults; $i++){
			$tab[$i] = $results[$i]->nodePath;
		}
		return $tab;
	}
	
	function display_all_results($results) {
	
		for($i=0; $i < count($nbResults); $i++){
			$resultDisplayed .= "Collection/".$results[$i]->documentName." ".$results[$i]->nodePath;
		}
		return $resultDisplayed;
	}
	
	function read_and_stock_node_path_file($fileName) {
		
		$tab = array();
		$handle = fopen($fileName, 'r');
		//Si on a réussi à ouvrir le fichier
		if ($handle)
		{
			$i = 0;
			//Tant que l'on est pas à la fin du fichier
			while (!feof($handle))
			{
				//On lit la ligne courante*/
				$buffer = fgets($handle);
				
				//Si non vide
				if (!empty($buffer)) {
					//On la stocke 
					$line = preg_split("/[\s]+/", $buffer);
					
					//On prend que les lignes avec une pertinence de 1
					if ($line[2] == "1"){
					
						$tab[$i] = $line[1];
						$i++;
					}
				}
			}
			//fermeture
			fclose($handle);
		}
		return $tab;
	}
	

	function getWeight($word, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $newParentTermForNode, $classesParams, $individualsParams){
		if(array_key_exists($word, $requestParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightParam'];
			}else{
				return $GLOBALS['weightParam'];
			}
		}else if(array_key_exists($word, $synonymesParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightSynonyme'] + 0.65;
			}else{
				return $GLOBALS['weightSynonyme'];
			}
			return $GLOBALS['weightSynonyme'];
		}else if(array_key_exists($word, $sonsParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightSons'] + 0.3;
			}else{
				return $GLOBALS['weightSons'];
			}
		}else if(array_key_exists($word, $dataPropParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightDataProp'] + 0.2;
			}else{
				return $GLOBALS['weightDataProp'];
			}
		}else if(array_key_exists($word, $objPropParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightObjProp'] +0.2 ;
			}else{
				return $GLOBALS['weightObjProp'];
			}
		}else if(array_key_exists($word, $classesParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightClasses'] +0.65 ;
			}else{
				return $GLOBALS['weightClasses'];
			}
		}else if(array_key_exists($word, $individualsParams)){
			if($newParentTermForNode == 1){
				return $GLOBALS['weightIndividuals'] +0.65 ;
			}else{
				return $GLOBALS['weightIndividuals'];
			}
		}else{
			if($newParentTermForNode == 1){
				return $GLOBALS['weightDefault'];
			}else{
				return $GLOBALS['weightDefault'];
			}
		}
	}
	
	function getParentTerm($word, $synonymesParams, $sonsParams, $dataPropParams, $objPropParams, $requestParams, $classesParams, $individualsParams){
		if(array_key_exists($word, $requestParams)){
			return $requestParams[$word] ;
		}else if(array_key_exists($word, $synonymesParams)){
			return $synonymesParams[$word] ;
		}else if(array_key_exists($word, $sonsParams)){
			return $sonsParams[$word] ;
		}else if(array_key_exists($word, $dataPropParams)){
			return $dataPropParams[$word] ;
		}else if(array_key_exists($word, $objPropParams)){
			return $objPropParams[$word] ;
		}else if(array_key_exists($word, $classesParams)){
			return $classesParams[$word] ;
		}else if(array_key_exists($word, $individualsParams)){
			return $individualsParams[$word] ;
		}else{
			return "";
		}
		
	}
	
	function buildTermRequest($tabParams){
		$requestStr = "SELECT term.value as termValue, termNode.frequency as termNodeFrequency,  node.path as nodePath, node.idNode as idNode, termnode.position as termnodePosition, termnode.weight as termnodeWeight, document.name as documentName, document.path as documentPath
									FROM term, node, termNode, document
									WHERE (";
		$nbParams = count($tabParams);
		$cpt = 1;
		foreach($tabParams as $param){
			if($cpt == $nbParams){
				$requestStr .= "term.value = '".$param."')";
			}else{
				$requestStr .= "term.value = '".$param."' or ";
			}
			$cpt++;
		}
		
		$requestStr .= " and termNode.idTerm = term.idTerm
									and node.idNode = termNode.idNode 
									and node.idDocument = document.idDocument";
									
		return $requestStr;
	}
	
	function connectionToOnto(){
		//Import lib sparql
		require_once( "./lib/sparqllib.php" );
		//Connection
		$db = sparql_connect("http://localhost:3030/space/query");

		if( !$db ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
		//Prefix
		sparql_ns( "rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#" );
		sparql_ns( "rdfs","http://www.w3.org/2000/01/rdf-schema#" );
		sparql_ns( "owl","http://www.w3.org/2002/07/owl#" );
		sparql_ns( "xsd","http://www.w3.org/2001/XMLSchema#" );
		sparql_ns( "ontologie","http://ontologies.alwaysdata.net/space#" );
		sparql_ns( "fn","http://www.w3.org/2005/xpath-functions#" );
	}

//Récupère tous les synonymes d'un label donné
function getSynonyme($base){
	connectionToOnto();
	//echo "<br/>Param SPARQL synonyme : ".$base;
	//Request to get synonyme
	$sparql = "SELECT ?synonyme WHERE { 
		?x rdfs:label ?label .
		?x rdfs:label ?synonyme .
		FILTER regex(?label,'".$base."', 'i')
	}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
}

//Récupére les labels des sous classes d'un parent
function getSonsLabel($parentLabel){
	connectionToOnto();
	
	$sparql = "SELECT DISTINCT ?sonLabel WHERE {
		?x rdfs:label ?label .
		?son rdfs:subClassOf{1} ?x .
		?son rdfs:label ?sonLabel.
		FILTER regex(?label,'".$parentLabel."', 'i').
	}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
	
}

//Recupère les objects properties pour un label donné
//En recupérant l'ontologie de l'objet puis en récupérant
//les objects properties de l'ontologie

function getObjectProperties($label){
	connectionToOnto();
	$sparql = "SELECT DISTINCT  ?labelObjProp
	WHERE {
		?x rdfs:label ?label .
		?objectProp rdfs:domain ?x.
		?objectProp a owl:ObjectProperty.
		?objectProp  rdfs:label ?labelObjProp.
		FILTER regex(?label,'".$label."', 'i').
	}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
}

//Get data properties for an object
function getDataProperties($label){
	connectionToOnto();
	$sparql = "SELECT DISTINCT  ?labelDataProp
	WHERE {
	?x rdfs:label ?label .
	?dataProp rdfs:domain ?x.
	?dataProp a owl:DatatypeProperty.
	?dataProp rdfs:label ?labelDataProp.
	FILTER regex(?label,'".$label."', 'i').
	}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
}

// Récupère les classes à partir d'une instance donnée
function getClasses($base){
	connectionToOnto();
	//echo "<br/>Param SPARQL classes : ".$base;
	//Request to get synonyme
	$sparql = "SELECT ?classeLabel WHERE {
		?x rdfs:label ?instance.
		?x a ?classe.
		?classe rdfs:label ?classeLabel.
		FILTER regex(?instance,'".$base."', 'i').
		}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
}

// Récupère les instances à partir du label d'une classe
function getIndividuals($base){
	connectionToOnto();
	//echo "<br/>Param SPARQL individuals : ".$base;
	//Request to get synonyme
	$sparql = "SELECT ?individual WHERE {
		?x rdfs:label ?individual.
		?x a ?y.
		?y rdfs:label ?classe.
		FILTER regex(?classe,'".$base."', 'i').
		}LIMIT 50";
	
	$result = sparql_query( $sparql ); 
	if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
	
	return $result;
}


//Affiche les résultat d'une requête
function displayResults($result){
	$fields = sparql_field_array( $result );

	//Display results and number results
	print "<p>Number of rows: ".sparql_num_rows( $result )." results.</p>";
	print "<table class='example_table' border='1'>";
	print "<tr>";
	foreach( $fields as $field )
	{
		print "<th>$field</th>";
	}
	print "</tr>";
	while( $row = sparql_fetch_array( $result ) )
	{
		print "<tr>";
		foreach( $fields as $field )
		{
			print "<td>$row[$field]</td>";
		}
		print "</tr>";
	}
	print "</table>";
}

function getContentResults($result){
	$fields = sparql_field_array( $result );
	$tabResult = array();
	//Get results
	while( $row = sparql_fetch_array( $result ) )
	{
		foreach( $fields as $field )
		{
			array_push($tabResult,$row[$field]);
		}
	}
	return $tabResult;
}

?>